// 游戏配置模块
class GameConfig {
    constructor() {
        this.speed = 150; // 蛇的基础移动速度（毫秒）
        this.difficulty = 'easy'; // 难度级别: 'easy', 'medium', 'hard'
        this.gridSize = 20; // 网格大小
        this.timeLimit = null; // 时间限制(秒)，null表示无限制
        this.obstacles = false; // 是否有障碍物
        this.theme = 'classic'; // 当前主题: 'classic', 'space', 'underwater', 'pixel'
        this.snakeSkin = 'default'; // 蛇的皮肤: 'default', 'neon', 'rainbow', 'metal'
    }

    // 根据难度设置速度
    setDifficultySpeed() {
        switch (this.difficulty) {
            case 'easy':
                this.speed = 150;
                break;
            case 'medium':
                this.speed = 100;
                break;
            case 'hard':
                this.speed = 70;
                break;
        }
    }

    // 设置游戏模式
    setGameMode(mode) {
        if (mode === 'timed') {
            this.timeLimit = 60; // 60秒限时模式
        } else {
            this.timeLimit = null; // 经典模式无时间限制
        }
    }
}

// 游戏状态模块
class GameState {
    constructor(gridSize) {
        this.gridSize = gridSize;
        this.reset();
    }

    reset() {
        // 初始化蛇的位置（居中）
        const centerX = Math.floor(this.gridSize / 2);
        const centerY = Math.floor(this.gridSize / 2);
        
        this.snake = [
            { x: centerX, y: centerY },
            { x: centerX - 1, y: centerY },
            { x: centerX - 2, y: centerY }
        ];
        
        this.direction = 'right';
        this.nextDirection = 'right'; // 用于防止快速连续按键导致的自杀
        this.food = { position: { x: 0, y: 0 }, type: 'normal' };
        this.score = 0;
        this.isGameOver = false;
        this.isPaused = false;
        this.remainingTime = null;
        this.obstacles = [];
        
        // 生成第一个食物
        this.generateFood();
    }

    // 生成食物
    generateFood() {
        // 食物类型概率: 普通(70%), 加分(20%), 缩短(10%)
        const foodTypes = ['normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'bonus', 'bonus', 'shrink'];
        const randomType = foodTypes[Math.floor(Math.random() * foodTypes.length)];
        
        let x, y;
        let validPosition = false;
        
        // 确保食物不会生成在蛇身上或障碍物上
        while (!validPosition) {
            x = Math.floor(Math.random() * this.gridSize);
            y = Math.floor(Math.random() * this.gridSize);
            
            validPosition = true;
            
            // 检查是否与蛇身重叠
            for (const segment of this.snake) {
                if (segment.x === x && segment.y === y) {
                    validPosition = false;
                    break;
                }
            }
            
            // 检查是否与障碍物重叠
            if (validPosition) {
                for (const obstacle of this.obstacles) {
                    if (obstacle.x === x && obstacle.y === y) {
                        validPosition = false;
                        break;
                    }
                }
            }
        }
        
        this.food = {
            position: { x, y },
            type: randomType
        };
    }

    // 生成障碍物
    generateObstacles(count) {
        this.obstacles = [];
        
        for (let i = 0; i < count; i++) {
            let x, y;
            let validPosition = false;
            
            while (!validPosition) {
                x = Math.floor(Math.random() * this.gridSize);
                y = Math.floor(Math.random() * this.gridSize);
                
                // 确保障碍物不会生成在蛇身上、食物上或其他障碍物上
                validPosition = true;
                
                // 检查是否与蛇身重叠（并留出蛇头周围的空间）
                for (const segment of this.snake) {
                    if ((segment.x === x && segment.y === y) || 
                        (Math.abs(this.snake[0].x - x) <= 2 && Math.abs(this.snake[0].y - y) <= 2)) {
                        validPosition = false;
                        break;
                    }
                }
                
                // 检查是否与食物重叠
                if (validPosition && this.food.position.x === x && this.food.position.y === y) {
                    validPosition = false;
                }
                
                // 检查是否与其他障碍物重叠
                if (validPosition) {
                    for (const obstacle of this.obstacles) {
                        if (obstacle.x === x && obstacle.y === y) {
                            validPosition = false;
                            break;
                        }
                    }
                }
            }
            
            this.obstacles.push({ x, y });
        }
    }

    // 更新方向
    setDirection(newDirection) {
        // 防止180度转弯（自杀）
        if (
            (this.direction === 'up' && newDirection === 'down') ||
            (this.direction === 'down' && newDirection === 'up') ||
            (this.direction === 'left' && newDirection === 'right') ||
            (this.direction === 'right' && newDirection === 'left')
        ) {
            return;
        }
        
        this.nextDirection = newDirection;
    }

    // 移动蛇
    moveSnake() {
        // 更新方向
        this.direction = this.nextDirection;
        
        // 获取蛇头
        const head = { ...this.snake[0] };
        
        // 根据方向移动蛇头
        switch (this.direction) {
            case 'up':
                head.y -= 1;
                break;
            case 'down':
                head.y += 1;
                break;
            case 'left':
                head.x -= 1;
                break;
            case 'right':
                head.x += 1;
                break;
        }
        
        // 检查是否吃到食物
        const ateFood = head.x === this.food.position.x && head.y === this.food.position.y;
        
        // 将新蛇头添加到蛇身数组前面
        this.snake.unshift(head);
        
        // 如果没有吃到食物，移除蛇尾；如果吃到了，保留蛇尾（蛇身变长）
        if (!ateFood) {
            this.snake.pop();
        } else {
            // 根据食物类型处理效果
            switch (this.food.type) {
                case 'normal':
                    // 普通食物：增加1分
                    this.score += 1;
                    break;
                case 'bonus':
                    // 加分食物：增加3分
                    this.score += 3;
                    break;
                case 'shrink':
                    // 缩短食物：减少蛇的长度（最少保留3个单位）
                    if (this.snake.length > 3) {
                        this.snake.pop();
                        this.snake.pop();
                    }
                    this.score += 1;
                    break;
            }
            
            // 生成新的食物
            this.generateFood();
            
            // 返回食物类型，用于动画效果
            return this.food.type;
        }
        
        return null;
    }

    // 检查碰撞
    checkCollision() {
        const head = this.snake[0];
        
        // 检查是否撞墙
        if (head.x < 0 || head.x >= this.gridSize || head.y < 0 || head.y >= this.gridSize) {
            return true;
        }
        
        // 检查是否撞到自己（从第二个身体部分开始检查）
        for (let i = 1; i < this.snake.length; i++) {
            if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
                return true;
            }
        }
        
        // 检查是否撞到障碍物
        for (const obstacle of this.obstacles) {
            if (head.x === obstacle.x && head.y === obstacle.y) {
                return true;
            }
        }
        
        return false;
    }

    // 更新时间（用于限时模式）
    updateTime(deltaTime) {
        if (this.remainingTime !== null) {
            this.remainingTime -= deltaTime;
            if (this.remainingTime <= 0) {
                this.remainingTime = 0;
                this.isGameOver = true;
                return true;
            }
        }
        return false;
    }
}

// 渲染器模块
class Renderer {
    constructor(canvasId, game) {
        this.canvas = document.getElementById(canvasId);
        this.ctx = this.canvas.getContext('2d');
        this.game = game;
        this.cellSize = this.canvas.width / game.state.gridSize;
        this.themeColors = this.getThemeColors();
        this.skinColors = this.getSkinColors();
    }

    // 添加init方法，修复错误
    init() {
        // 初始化渲染器
        this.cellSize = this.canvas.width / this.game.state.gridSize;
        this.themeColors = this.getThemeColors();
        this.skinColors = this.getSkinColors();
    }

    // 获取主题颜色
    getThemeColors() {
        return {
            classic: {
                background: '#1f2937',
                gridLines: '#374151',
                foodNormal: '#ef4444',
                foodBonus: '#f59e0b',
                foodShrink: '#10b981',
                obstacle: '#6b7280'
            },
            space: {
                background: '#0f172a',
                gridLines: '#1e293b',
                foodNormal: '#f97316',
                foodBonus: '#facc15',
                foodShrink: '#22d3ee',
                obstacle: '#475569'
            },
            underwater: {
                background: '#0c4a6e',
                gridLines: '#0369a1',
                foodNormal: '#fbbf24',
                foodBonus: '#fb923c',
                foodShrink: '#34d399',
                obstacle: '#0891b2'
            },
            pixel: {
                background: '#18181b',
                gridLines: '#27272a',
                foodNormal: '#fb7185',
                foodBonus: '#fbbf24',
                foodShrink: '#84cc16',
                obstacle: '#52525b'
            }
        };
    }

    // 获取蛇皮肤颜色
    getSkinColors() {
        return {
            default: {
                head: '#4f46e5',
                body: '#6366f1',
                pattern: null
            },
            neon: {
                head: '#22d3ee',
                body: '#67e8f9',
                pattern: 'glow'
            },
            rainbow: {
                head: '#ef4444',
                body: 'rainbow',
                pattern: null
            },
            metal: {
                head: '#94a3b8',
                body: '#cbd5e1',
                pattern: 'gradient'
            }
        };
    }

    // 清除画布
    clear() {
        const theme = this.themeColors[this.game.config.theme];
        this.ctx.fillStyle = theme.background;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格线（根据主题）
        if (this.game.config.theme === 'pixel') {
            this.drawPixelGrid();
        }
    }

    // 绘制像素风格网格
    drawPixelGrid() {
        const theme = this.themeColors[this.game.config.theme];
        this.ctx.strokeStyle = theme.gridLines;
        this.ctx.lineWidth = 0.5;
        
        for (let i = 0; i <= this.game.state.gridSize; i++) {
            const pos = i * this.cellSize;
            
            // 水平线
            this.ctx.beginPath();
            this.ctx.moveTo(0, pos);
            this.ctx.lineTo(this.canvas.width, pos);
            this.ctx.stroke();
            
            // 垂直线
            this.ctx.beginPath();
            this.ctx.moveTo(pos, 0);
            this.ctx.lineTo(pos, this.canvas.height);
            this.ctx.stroke();
        }
    }

    // 绘制蛇
    drawSnake() {
        const { snake } = this.game.state;
        const skin = this.skinColors[this.game.config.snakeSkin];
        
        // 绘制蛇身
        for (let i = snake.length - 1; i >= 0; i--) {
            const segment = snake[i];
            const x = segment.x * this.cellSize;
            const y = segment.y * this.cellSize;
            
            // 确定颜色（头部、身体可能有不同颜色）
            let fillStyle;
            
            if (i === 0) {
                // 蛇头
                fillStyle = skin.head;
            } else {
                // 蛇身
                if (skin.body === 'rainbow') {
                    // 彩虹皮肤：根据位置使用不同颜色
                    const hue = (i * 30) % 360;
                    fillStyle = `hsl(${hue}, 100%, 60%)`;
                } else {
                    fillStyle = skin.body;
                }
            }
            
            this.ctx.fillStyle = fillStyle;
            
            // 绘制圆角矩形作为蛇的身体部分
            this.roundRect(
                x + 1, 
                y + 1, 
                this.cellSize - 2, 
                this.cellSize - 2, 
                4
            );
            
            // 为霓虹皮肤添加发光效果
            if (skin.pattern === 'glow') {
                this.ctx.shadowColor = skin.head;
                this.ctx.shadowBlur = 10;
                this.ctx.fill();
                this.ctx.shadowBlur = 0;
            } else {
                this.ctx.fill();
            }
            
            // 为金属皮肤添加渐变效果
            if (skin.pattern === 'gradient' && i === 0) {
                const gradient = this.ctx.createLinearGradient(x, y, x + this.cellSize, y + this.cellSize);
                gradient.addColorStop(0, '#94a3b8');
                gradient.addColorStop(0.5, '#e2e8f0');
                gradient.addColorStop(1, '#94a3b8');
                
                this.ctx.fillStyle = gradient;
                this.roundRect(
                    x + this.cellSize / 4, 
                    y + this.cellSize / 4, 
                    this.cellSize / 2, 
                    this.cellSize / 2, 
                    2
                );
                this.ctx.fill();
            }
            
            // 绘制蛇眼睛（只在蛇头上）
            if (i === 0) {
                this.drawSnakeEyes(segment);
            }
        }
    }

    // 绘制蛇眼睛
    drawSnakeEyes(head) {
        const x = head.x * this.cellSize;
        const y = head.y * this.cellSize;
        const direction = this.game.state.direction;
        
        this.ctx.fillStyle = 'white';
        
        // 根据方向确定眼睛位置
        let leftEyeX, leftEyeY, rightEyeX, rightEyeY;
        
        switch (direction) {
            case 'up':
                leftEyeX = x + this.cellSize / 4;
                leftEyeY = y + this.cellSize / 4;
                rightEyeX = x + this.cellSize * 3 / 4;
                rightEyeY = y + this.cellSize / 4;
                break;
            case 'down':
                leftEyeX = x + this.cellSize / 4;
                leftEyeY = y + this.cellSize * 3 / 4;
                rightEyeX = x + this.cellSize * 3 / 4;
                rightEyeY = y + this.cellSize * 3 / 4;
                break;
            case 'left':
                leftEyeX = x + this.cellSize / 4;
                leftEyeY = y + this.cellSize / 4;
                rightEyeX = x + this.cellSize / 4;
                rightEyeY = y + this.cellSize * 3 / 4;
                break;
            case 'right':
                leftEyeX = x + this.cellSize * 3 / 4;
                leftEyeY = y + this.cellSize / 4;
                rightEyeX = x + this.cellSize * 3 / 4;
                rightEyeY = y + this.cellSize * 3 / 4;
                break;
        }
        
        // 绘制眼白
        const eyeSize = this.cellSize / 5;
        this.ctx.beginPath();
        this.ctx.arc(leftEyeX, leftEyeY, eyeSize, 0, Math.PI * 2);
        this.ctx.fill();
        
        this.ctx.beginPath();
        this.ctx.arc(rightEyeX, rightEyeY, eyeSize, 0, Math.PI * 2);
        this.ctx.fill();
        
        // 绘制眼球
        this.ctx.fillStyle = 'black';
        const pupilSize = eyeSize / 2;
        
        // 左眼球
        this.ctx.beginPath();
        this.ctx.arc(
            leftEyeX + (direction === 'right' ? pupilSize / 2 : direction === 'left' ? -pupilSize / 2 : 0),
            leftEyeY + (direction === 'down' ? pupilSize / 2 : direction === 'up' ? -pupilSize / 2 : 0),
            pupilSize, 
            0, 
            Math.PI * 2
        );
        this.ctx.fill();
        
        // 右眼球
        this.ctx.beginPath();
        this.ctx.arc(
            rightEyeX + (direction === 'right' ? pupilSize / 2 : direction === 'left' ? -pupilSize / 2 : 0),
            rightEyeY + (direction === 'down' ? pupilSize / 2 : direction === 'up' ? -pupilSize / 2 : 0),
            pupilSize, 
            0, 
            Math.PI * 2
        );
        this.ctx.fill();
    }

    // 绘制食物
    drawFood() {
        const { position, type } = this.game.state.food;
        const theme = this.themeColors[this.game.config.theme];
        
        const x = position.x * this.cellSize;
        const y = position.y * this.cellSize;
        
        // 根据食物类型选择颜色
        switch (type) {
            case 'normal':
                this.ctx.fillStyle = theme.foodNormal;
                break;
            case 'bonus':
                this.ctx.fillStyle = theme.foodBonus;
                break;
            case 'shrink':
                this.ctx.fillStyle = theme.foodShrink;
                break;
        }
        
        // 绘制食物（圆形）
        this.ctx.beginPath();
        this.ctx.arc(
            x + this.cellSize / 2,
            y + this.cellSize / 2,
            this.cellSize / 2 - 2,
            0,
            Math.PI * 2
        );
        this.ctx.fill();
        
        // 为食物添加发光效果（太空主题）
        if (this.game.config.theme === 'space') {
            this.ctx.shadowColor = this.ctx.fillStyle;
            this.ctx.shadowBlur = 10;
            this.ctx.fill();
            this.ctx.shadowBlur = 0;
        }
        
        // 为加分食物添加星形图案
        if (type === 'bonus') {
            this.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
            this.drawStar(
                x + this.cellSize / 2,
                y + this.cellSize / 2,
                5,
                this.cellSize / 4,
                this.cellSize / 8
            );
        }
        
        // 为缩短食物添加减号图案
        if (type === 'shrink') {
            this.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
            this.ctx.fillRect(
                x + this.cellSize / 4,
                y + this.cellSize / 2 - 2,
                this.cellSize / 2,
                4
            );
        }
    }

    // 绘制星形（用于加分食物）
    drawStar(cx, cy, spikes, outerRadius, innerRadius) {
        let rot = Math.PI / 2 * 3;
        let x = cx;
        let y = cy;
        const step = Math.PI / spikes;

        this.ctx.beginPath();
        this.ctx.moveTo(cx, cy - outerRadius);
        
        for (let i = 0; i < spikes; i++) {
            x = cx + Math.cos(rot) * outerRadius;
            y = cy + Math.sin(rot) * outerRadius;
            this.ctx.lineTo(x, y);
            rot += step;

            x = cx + Math.cos(rot) * innerRadius;
            y = cy + Math.sin(rot) * innerRadius;
            this.ctx.lineTo(x, y);
            rot += step;
        }
        
        this.ctx.lineTo(cx, cy - outerRadius);
        this.ctx.closePath();
        this.ctx.fill();
    }

    // 绘制障碍物
    drawObstacles() {
        const { obstacles } = this.game.state;
        const theme = this.themeColors[this.game.config.theme];
        
        this.ctx.fillStyle = theme.obstacle;
        
        for (const obstacle of obstacles) {
            const x = obstacle.x * this.cellSize;
            const y = obstacle.y * this.cellSize;
            
            // 根据主题绘制不同样式的障碍物
            switch (this.game.config.theme) {
                case 'classic':
                    // 经典主题：简单方块
                    this.ctx.fillRect(x, y, this.cellSize, this.cellSize);
                    break;
                    
                case 'space':
                    // 太空主题：小行星
                    this.ctx.beginPath();
                    this.ctx.arc(
                        x + this.cellSize / 2,
                        y + this.cellSize / 2,
                        this.cellSize / 2,
                        0,
                        Math.PI * 2
                    );
                    this.ctx.fill();
                    
                    // 添加陨石纹理
                    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
                    this.ctx.beginPath();
                    this.ctx.arc(
                        x + this.cellSize / 3,
                        y + this.cellSize / 3,
                        this.cellSize / 6,
                        0,
                        Math.PI * 2
                    );
                    this.ctx.fill();
                    break;
                    
                case 'underwater':
                    // 海底主题：珊瑚
                    this.drawCoral(x, y);
                    break;
                    
                case 'pixel': {
                    // 像素主题：像素块
                    const blockSize = this.cellSize / 4;
                    for (let i = 0; i < 4; i++) {
                        for (let j = 0; j < 4; j++) {
                            if ((i + j) % 2 === 0) {
                                this.ctx.fillRect(
                                    x + i * blockSize,
                                    y + j * blockSize,
                                    blockSize,
                                    blockSize
                                );
                            }
                        }
                    }
                    break;
                }
            }
        }
    }

    // 绘制珊瑚（海底主题障碍物）
    drawCoral(x, y) {
        this.ctx.fillStyle = this.themeColors.underwater.obstacle;
        
        // 珊瑚基座
        this.ctx.fillRect(
            x + this.cellSize / 4,
            y + this.cellSize / 2,
            this.cellSize / 2,
            this.cellSize / 2
        );
        
        // 珊瑚分支
        this.ctx.beginPath();
        this.ctx.arc(
            x + this.cellSize / 4,
            y + this.cellSize / 2,
            this.cellSize / 4,
            Math.PI,
            Math.PI * 2
        );
        this.ctx.fill();
        
        this.ctx.beginPath();
        this.ctx.arc(
            x + this.cellSize * 3 / 4,
            y + this.cellSize / 2,
            this.cellSize / 4,
            Math.PI,
            Math.PI * 2
        );
        this.ctx.fill();
        
        this.ctx.beginPath();
        this.ctx.arc(
            x + this.cellSize / 2,
            y + this.cellSize / 3,
            this.cellSize / 4,
            Math.PI,
            Math.PI * 2
        );
        this.ctx.fill();
    }

    // 绘制背景效果
    drawBackground() {
        switch (this.game.config.theme) {
            case 'space':
                this.drawStars();
                break;
            case 'underwater':
                this.drawBubbles();
                break;
            case 'pixel':
                // 像素主题的背景已经在clear()中绘制了网格
                break;
        }
    }

    // 绘制星星（太空主题）
    drawStars() {
        this.ctx.fillStyle = 'white';
        
        // 使用伪随机数生成固定位置的星星
        let seedValue = 12345;
        const random = (max) => {
            seedValue = (seedValue * 9301 + 49297) % 233280;
            return (seedValue / 233280) * max;
        };
        
        for (let i = 0; i < 100; i++) {
            const x = random(this.canvas.width);
            const y = random(this.canvas.height);
            const size = random(2) + 0.5;
            
            this.ctx.beginPath();
            this.ctx.arc(x, y, size, 0, Math.PI * 2);
            this.ctx.fill();
            
            // 一些星星有发光效果
            if (i % 10 === 0) {
                this.ctx.shadowColor = 'white';
                this.ctx.shadowBlur = 5;
                this.ctx.fill();
                this.ctx.shadowBlur = 0;
            }
        }
    }

    // 绘制气泡（海底主题）
    drawBubbles() {
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
        
        // 使用当前时间作为动画偏移
        const timeOffset = Date.now() / 1000;
        
        for (let i = 0; i < 20; i++) {
            const x = ((i * 37) % this.canvas.width) + Math.sin((timeOffset + i) / 2) * 20;
            const y = (this.canvas.height - ((timeOffset * 20 + i * 50) % this.canvas.height));
            const size = (i % 4) + 2;
            
            this.ctx.beginPath();
            this.ctx.arc(x, y, size, 0, Math.PI * 2);
            this.ctx.fill();
        }
    }

    // 绘制圆角矩形
    roundRect(x, y, width, height, radius) {
        this.ctx.beginPath();
        this.ctx.moveTo(x + radius, y);
        this.ctx.lineTo(x + width - radius, y);
        this.ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        this.ctx.lineTo(x + width, y + height - radius);
        this.ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        this.ctx.lineTo(x + radius, y + height);
        this.ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        this.ctx.lineTo(x, y + radius);
        this.ctx.quadraticCurveTo(x, y, x + radius, y);
        this.ctx.closePath();
    }

    // 渲染游戏
    render() {
        this.clear();
        this.drawBackground();
        this.drawObstacles();
        this.drawFood();
        this.drawSnake();
    }
}

// 控制器模块
class Controller {
    constructor(game) {
        this.game = game;
        this.touchStartX = 0;
        this.touchStartY = 0;
    }

    // 初始化控制器
    init() {
        this.setupKeyboardControls();
        this.setupTouchControls();
        this.setupVirtualControls();
    }

    // 设置键盘控制
    setupKeyboardControls() {
        document.addEventListener('keydown', (e) => {
            if (this.game.state.isGameOver || this.game.state.isPaused) return;
            
            switch (e.key) {
                case 'ArrowUp':
                    this.game.state.setDirection('up');
                    e.preventDefault();
                    break;
                case 'ArrowDown':
                    this.game.state.setDirection('down');
                    e.preventDefault();
                    break;
                case 'ArrowLeft':
                    this.game.state.setDirection('left');
                    e.preventDefault();
                    break;
                case 'ArrowRight':
                    this.game.state.setDirection('right');
                    e.preventDefault();
                    break;
                case 'Escape':
                    this.game.togglePause();
                    e.preventDefault();
                    break;
            }
        });
    }

    // 设置触摸控制
    setupTouchControls() {
        const canvas = document.getElementById('game-canvas');
        
        canvas.addEventListener('touchstart', (e) => {
            this.touchStartX = e.touches[0].clientX;
            this.touchStartY = e.touches[0].clientY;
            e.preventDefault();
        }, { passive: false });
        
        canvas.addEventListener('touchmove', (e) => {
            if (this.game.state.isGameOver || this.game.state.isPaused) return;
            
            const touchEndX = e.touches[0].clientX;
            const touchEndY = e.touches[0].clientY;
            
            const dx = touchEndX - this.touchStartX;
            const dy = touchEndY - this.touchStartY;
            
            // 需要有足够的滑动距离才触发方向变化
            const minSwipeDistance = 30;
            
            if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > minSwipeDistance) {
                // 水平滑动
                if (dx > 0) {
                    this.game.state.setDirection('right');
                } else {
                    this.game.state.setDirection('left');
                }
            } else if (Math.abs(dy) > Math.abs(dx) && Math.abs(dy) > minSwipeDistance) {
                // 垂直滑动
                if (dy > 0) {
                    this.game.state.setDirection('down');
                } else {
                    this.game.state.setDirection('up');
                }
            }
            
            // 更新起始位置，使连续滑动更流畅
            this.touchStartX = touchEndX;
            this.touchStartY = touchEndY;
            
            e.preventDefault();
        }, { passive: false });
    }

    // 设置虚拟方向键
    setupVirtualControls() {
        const virtualBtns = document.querySelectorAll('.virtual-btn');
        
        virtualBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                if (this.game.state.isGameOver || this.game.state.isPaused) return;
                
                const direction = btn.getAttribute('data-direction');
                this.game.state.setDirection(direction);
            });
        });
        
        // 检测是否为移动设备，显示虚拟控制按钮
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            document.getElementById('virtual-controls').classList.remove('hidden');
        }
    }
}

// 动画管理器模块
class AnimationManager {
    constructor(game) {
        this.game = game;
        this.animations = new Map();
        this.anime = window.anime;
    }

    // 初始化动画
    init() {
        // 预设一些动画
    }

    // 食物被吃掉的动画
    foodEatenAnimation(position, foodType) {
        const canvas = document.getElementById('game-canvas');
        const cellSize = canvas.width / this.game.state.gridSize;
        
        // 创建一个临时元素用于动画
        const element = document.createElement('div');
        element.className = `food-animation food-${foodType}`;
        element.style.position = 'absolute';
        element.style.width = `${cellSize}px`;
        element.style.height = `${cellSize}px`;
        element.style.borderRadius = '50%';
        element.style.left = `${position.x * cellSize + canvas.offsetLeft}px`;
        element.style.top = `${position.y * cellSize + canvas.offsetTop}px`;
        
        // 设置颜色
        switch (foodType) {
            case 'normal':
                element.style.backgroundColor = '#ef4444';
                break;
            case 'bonus':
                element.style.backgroundColor = '#f59e0b';
                break;
            case 'shrink':
                element.style.backgroundColor = '#10b981';
                break;
        }
        
        document.getElementById('game-area').appendChild(element);
        
        // 使用anime.js创建动画
        this.anime({
            targets: element,
            scale: [1, 1.5],
            opacity: [1, 0],
            easing: 'easeOutExpo',
            duration: 600,
            complete: () => {
                element.remove();
            }
        });
        
        // 根据食物类型添加分数动画
        let scoreValue;
        switch (foodType) {
            case 'normal':
                scoreValue = '+1';
                break;
            case 'bonus':
                scoreValue = '+3';
                break;
            case 'shrink':
                scoreValue = '-2 长度';
                break;
        }
        
        const scoreElement = document.createElement('div');
        scoreElement.textContent = scoreValue;
        scoreElement.style.position = 'absolute';
        scoreElement.style.left = `${position.x * cellSize + canvas.offsetLeft}px`;
        scoreElement.style.top = `${position.y * cellSize + canvas.offsetTop - 20}px`;
        scoreElement.style.color = 'white';
        scoreElement.style.fontWeight = 'bold';
        scoreElement.style.textShadow = '0 0 3px black';
        
        document.getElementById('game-area').appendChild(scoreElement);
        
        this.anime({
            targets: scoreElement,
            translateY: -30,
            opacity: [1, 0],
            easing: 'easeOutExpo',
            duration: 1000,
            complete: () => {
                scoreElement.remove();
            }
        });
    }

    // 游戏结束动画
    gameOverAnimation() {
        const canvas = document.getElementById('game-canvas');
        
        // 创建闪烁效果
        this.anime({
            targets: canvas,
            opacity: [1, 0.5, 1],
            easing: 'easeInOutSine',
            duration: 500,
            complete: () => {
                // 显示游戏结束菜单
                document.getElementById('game-over').classList.remove('hidden');
                document.getElementById('final-score').textContent = this.game.state.score;
                
                // 添加菜单出现动画
                this.anime({
                    targets: '#game-over',
                    opacity: [0, 1],
                    scale: [0.9, 1],
                    easing: 'easeOutExpo',
                    duration: 600
                });
            }
        });
    }

    // 主题切换动画
    themeTransitionAnimation(oldTheme, newTheme) {
        const canvas = document.getElementById('game-canvas');
        
        this.anime({
            targets: canvas,
            opacity: [1, 0, 1],
            easing: 'easeInOutSine',
            duration: 500,
            update: (anim) => {
                // 在动画中间点切换主题
                if (anim.progress >= 50 && oldTheme !== newTheme) {
                    this.game.config.theme = newTheme;
                    this.game.renderer.themeColors = this.game.renderer.getThemeColors();
                    this.game.renderer.render();
                }
            }
        });
    }

    // 皮肤切换动画
    skinTransitionAnimation(oldSkin, newSkin) {
        const canvas = document.getElementById('game-canvas');
        
        this.anime({
            targets: canvas,
            scale: [1, 0.95, 1],
            easing: 'easeInOutSine',
            duration: 300,
            update: (anim) => {
                // 在动画中间点切换皮肤
                if (anim.progress >= 50 && oldSkin !== newSkin) {
                    this.game.config.snakeSkin = newSkin;
                    this.game.renderer.skinColors = this.game.renderer.getSkinColors();
                    this.game.renderer.render();
                }
            }
        });
    }

    // 菜单切换动画
    menuTransitionAnimation(hideMenuId, showMenuId) {
        const hideMenu = document.getElementById(hideMenuId);
        const showMenu = document.getElementById(showMenuId);
        
        // 隐藏当前菜单
        this.anime({
            targets: hideMenu,
            opacity: [1, 0],
            scale: [1, 0.9],
            easing: 'easeInOutSine',
            duration: 300,
            complete: () => {
                hideMenu.classList.add('hidden');
                showMenu.classList.remove('hidden');
                showMenu.style.opacity = 0;
                showMenu.style.transform = 'scale(0.9)';
                
                // 显示新菜单
                this.anime({
                    targets: showMenu,
                    opacity: [0, 1],
                    scale: [0.9, 1],
                    easing: 'easeOutExpo',
                    duration: 300
                });
            }
        });
    }
}

// 用户界面模块
class UI {
    constructor(game) {
        this.game = game;
    }

    // 初始化UI
    init() {
        this.setupEventListeners();
        this.updateScoreDisplay(0);
    }

    // 设置事件监听器
    setupEventListeners() {
        // 主菜单按钮
        document.getElementById('start-game').addEventListener('click', () => {
            this.hideAllMenus();
            this.game.start();
        });
        
        document.getElementById('settings-btn').addEventListener('click', () => {
            this.game.animationManager.menuTransitionAnimation('main-menu', 'settings-menu');
        });
        
        document.getElementById('theme-btn').addEventListener('click', () => {
            this.game.animationManager.menuTransitionAnimation('main-menu', 'theme-menu');
        });
        
        document.getElementById('skin-btn').addEventListener('click', () => {
            this.game.animationManager.menuTransitionAnimation('main-menu', 'skin-menu');
        });
        
        // 设置菜单按钮
        document.getElementById('settings-back').addEventListener('click', () => {
            this.game.animationManager.menuTransitionAnimation('settings-menu', 'main-menu');
        });
        
        // 难度按钮
        const difficultyBtns = document.querySelectorAll('.difficulty-btn');
        difficultyBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                difficultyBtns.forEach(b => b.classList.remove('selected'));
                btn.classList.add('selected');
                this.game.config.difficulty = btn.getAttribute('data-difficulty');
                this.game.config.setDifficultySpeed();
            });
        });
        
        // 游戏模式按钮
        const modeBtns = document.querySelectorAll('.mode-btn');
        modeBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                modeBtns.forEach(b => b.classList.remove('selected'));
                btn.classList.add('selected');
                this.game.config.setGameMode(btn.getAttribute('data-mode'));
                
                // 更新时间显示
                const timeDisplay = document.getElementById('time-display');
                if (this.game.config.timeLimit !== null) {
                    timeDisplay.classList.remove('hidden');
                    document.getElementById('time').textContent = this.game.config.timeLimit;
                } else {
                    timeDisplay.classList.add('hidden');
                }
            });
        });
        
        // 障碍物开关
        document.getElementById('obstacles-toggle').addEventListener('change', (e) => {
            this.game.config.obstacles = e.target.checked;
        });
        
        // 主题菜单按钮
        document.getElementById('theme-back').addEventListener('click', () => {
            this.game.animationManager.menuTransitionAnimation('theme-menu', 'main-menu');
        });
        
        // 主题选项
        const themeOptions = document.querySelectorAll('.theme-option');
        themeOptions.forEach(option => {
            option.addEventListener('click', () => {
                const oldTheme = this.game.config.theme;
                const newTheme = option.getAttribute('data-theme');
                
                themeOptions.forEach(o => o.classList.remove('selected'));
                option.classList.add('selected');
                
                this.game.animationManager.themeTransitionAnimation(oldTheme, newTheme);
            });
        });
        
        // 皮肤菜单按钮
        document.getElementById('skin-back').addEventListener('click', () => {
            this.game.animationManager.menuTransitionAnimation('skin-menu', 'main-menu');
        });
        
        // 皮肤选项
        const skinOptions = document.querySelectorAll('.skin-option');
        skinOptions.forEach(option => {
            option.addEventListener('click', () => {
                const oldSkin = this.game.config.snakeSkin;
                const newSkin = option.getAttribute('data-skin');
                
                skinOptions.forEach(o => o.classList.remove('selected'));
                option.classList.add('selected');
                
                this.game.animationManager.skinTransitionAnimation(oldSkin, newSkin);
            });
        });
        
        // 暂停菜单按钮
        document.getElementById('resume-game').addEventListener('click', () => {
            this.hidePauseMenu();
            this.game.resume();
        });
        
        document.getElementById('restart-game').addEventListener('click', () => {
            this.hideAllMenus();
            this.game.reset();
            this.game.start();
        });
        
        document.getElementById('exit-to-menu').addEventListener('click', () => {
            this.hideAllMenus();
            document.getElementById('main-menu').classList.remove('hidden');
        });
        
        // 游戏结束菜单按钮
        document.getElementById('play-again').addEventListener('click', () => {
            this.hideAllMenus();
            this.game.reset();
            this.game.start();
        });
        
        document.getElementById('game-over-menu').addEventListener('click', () => {
            this.hideAllMenus();
            document.getElementById('main-menu').classList.remove('hidden');
        });
        
        // 初始化选中状态
        document.querySelector(`.theme-option[data-theme="${this.game.config.theme}"]`).classList.add('selected');
        document.querySelector(`.skin-option[data-skin="${this.game.config.snakeSkin}"]`).classList.add('selected');
    }

    // 隐藏所有菜单
    hideAllMenus() {
        const menus = ['main-menu', 'settings-menu', 'theme-menu', 'skin-menu', 'pause-menu', 'game-over'];
        menus.forEach(menuId => {
            document.getElementById(menuId).classList.add('hidden');
        });
    }

    // 显示暂停菜单
    showPauseMenu() {
        document.getElementById('pause-menu').classList.remove('hidden');
    }

    // 隐藏暂停菜单
    hidePauseMenu() {
        document.getElementById('pause-menu').classList.add('hidden');
    }

    // 更新分数显示
    updateScoreDisplay(score) {
        document.getElementById('score').textContent = score;
    }

    // 更新时间显示
    updateTimeDisplay(time) {
        if (time !== null) {
            document.getElementById('time').textContent = Math.ceil(time);
        }
    }
}

// 游戏主类
class Game {
    constructor() {
        this.config = new GameConfig();
        this.state = new GameState(this.config.gridSize);
        this.renderer = new Renderer('game-canvas', this);
        this.controller = new Controller(this);
        this.animationManager = new AnimationManager(this);
        this.ui = new UI(this);
        
        this.lastUpdateTime = 0;
        this.gameLoopId = null;
    }

    // 初始化游戏
    init() {
        this.renderer.init();
        this.controller.init();
        this.animationManager.init();
        this.ui.init();
        
        // 初始渲染
        this.renderer.render();
    }

    // 开始游戏
    start() {
        if (this.gameLoopId) {
            cancelAnimationFrame(this.gameLoopId);
        }
        
        // 重置游戏状态
        this.reset();
        
        this.state.isPaused = false;
        this.lastUpdateTime = performance.now();
        
        // 如果有障碍物，生成障碍物
        if (this.config.obstacles) {
            // 障碍物数量根据难度调整
            let obstacleCount;
            switch (this.config.difficulty) {
                case 'easy':
                    obstacleCount = 3;
                    break;
                case 'medium':
                    obstacleCount = 5;
                    break;
                case 'hard':
                    obstacleCount = 8;
                    break;
                default:
                    obstacleCount = 3;
            }
            
            this.state.generateObstacles(obstacleCount);
        }
        
        // 设置剩余时间（如果是限时模式）
        if (this.config.timeLimit !== null) {
            this.state.remainingTime = this.config.timeLimit;
            document.getElementById('time-display').classList.remove('hidden');
            this.ui.updateTimeDisplay(this.state.remainingTime);
        } else {
            document.getElementById('time-display').classList.add('hidden');
        }
        
        this.gameLoop();
    }

    // 游戏主循环
    gameLoop() {
        const currentTime = performance.now();
        const deltaTime = (currentTime - this.lastUpdateTime) / 1000; // 转换为秒
        
        // 更新游戏状态
        if (!this.state.isPaused && !this.state.isGameOver) {
            // 检查是否需要更新（基于速度）
            if (currentTime - this.lastUpdateTime >= this.config.speed) {
                this.update();
                this.lastUpdateTime = currentTime;
            }
            
            // 更新时间（如果是限时模式）
            if (this.state.remainingTime !== null) {
                const timeOver = this.state.updateTime(deltaTime);
                this.ui.updateTimeDisplay(this.state.remainingTime);
                
                if (timeOver) {
                    this.gameOver();
                }
            }
        }
        
        // 渲染游戏
        this.renderer.render();
        
        // 继续游戏循环
        if (!this.state.isGameOver) {
            this.gameLoopId = requestAnimationFrame(() => this.gameLoop());
        }
    }

    // 更新游戏状态
    update() {
        // 移动蛇
        const foodType = this.state.moveSnake();
        
        // 检查是否吃到食物
        if (foodType) {
            // 播放食物吃掉动画
            this.animationManager.foodEatenAnimation(this.state.food.position, foodType);
            
            // 更新分数显示
            this.ui.updateScoreDisplay(this.state.score);
            
            // 根据分数增加速度（每10分加快一点）
            if (this.state.score % 10 === 0) {
                this.config.speed = Math.max(50, this.config.speed - 5);
            }
        }
        
        // 检查碰撞
        if (this.state.checkCollision()) {
            this.gameOver();
        }
    }

    // 游戏结束
    gameOver() {
        this.state.isGameOver = true;
        cancelAnimationFrame(this.gameLoopId);
        
        // 播放游戏结束动画
        this.animationManager.gameOverAnimation();
    }

    // 暂停游戏
    togglePause() {
        if (this.state.isGameOver) return;
        
        this.state.isPaused = !this.state.isPaused;
        
        if (this.state.isPaused) {
            this.ui.showPauseMenu();
        } else {
            this.ui.hidePauseMenu();
        }
    }

    // 恢复游戏
    resume() {
        if (this.state.isPaused) {
            this.state.isPaused = false;
            this.lastUpdateTime = performance.now();
        }
    }

    // 重置游戏
    reset() {
        this.state.reset();
        this.ui.updateScoreDisplay(0);
        this.config.setDifficultySpeed();
        
        // 确保游戏结束菜单被隐藏
        document.getElementById('game-over').classList.add('hidden');
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    const game = new Game();
    game.init();
    
    // 检测移动设备并调整布局
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        const canvas = document.getElementById('game-canvas');
        const gameArea = document.getElementById('game-area');
        
        // 调整画布大小以适应移动设备
        const screenWidth = Math.min(window.innerWidth - 20, 400);
        canvas.width = screenWidth;
        canvas.height = screenWidth;
        
        // 重新计算单元格大小
        game.renderer.cellSize = canvas.width / game.state.gridSize;
    }
});